package com.yape.webCrawler.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yape.annotation.CrawlerLog;
import com.yape.webCrawler.base.BaseCrawler;
import com.yape.webCrawler.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;

/**
 * @Author Hazuki
 * @Date 2025/5/23 下午3:15
 * @Version 1.0
 */
@Slf4j
@Component("newsCount")
public class FastNewsCountCrawler extends BaseCrawler {
    private static final String COUNT_URL_TEMPLATE =
            "https://np-weblist.eastmoney.com/comm/web/getFastNewsCount?client=web&biz=web_724&fastColumn=102%s&req_trace=%d&_=%d&callback=jQuery123456_%s";

    private long currentReqTrace = System.currentTimeMillis();

    @CrawlerLog
    @Override
    public Object execute() throws IOException {
        // sortStart 设置为当日0点
        long zeroMillis = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        String sortStart = String.valueOf(zeroMillis);
        String sortStartParam = "";
        if (sortStart != null && !sortStart.isEmpty()) {
            sortStartParam = "&sortStart=" + sortStart;
        }

        long cacheParam = currentReqTrace + 1;
        String callbackId = String.valueOf(currentReqTrace);

        String url = String.format(COUNT_URL_TEMPLATE,
                sortStartParam,
                currentReqTrace,
                cacheParam,
                callbackId);

        log.info("请求URL: {}", url);

        String jsonpResponse = Jsoup.connect(url)
                .ignoreContentType(true)
                .execute()
                .body();

        String jsonResponse = JsonUtils.extractJsonFromJsonp(jsonpResponse);
        JsonNode rootNode = new ObjectMapper().readTree(jsonResponse);
        int count = rootNode.path("data").path("count").asInt();

        log.info("快讯数量: {}", count);

        // Update reqTrace for next call
        currentReqTrace = System.currentTimeMillis();

        return count;
    }



    @Override
    protected String getApiUrl() {
        long cacheParam = currentReqTrace + 1;
        String callbackId = String.valueOf(currentReqTrace);

        return String.format(COUNT_URL_TEMPLATE,
                "",
                currentReqTrace,
                cacheParam,
                callbackId);
    }
}